package com.movie.service.impl;

import com.movie.entity.User;
import com.movie.mapper.UserMapper;
import com.movie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.HashMap;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    // 实现 UserService 接口中定义的方法
    // ... 稍后添加实现 ...

    @Override
    public User register(User user) {
        if (userMapper.existsByUsername(user.getUsername()) > 0) {
            throw new RuntimeException("Username already exists: " + user.getUsername());
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setRegisterTime(LocalDateTime.now());
        userMapper.insert(user);
        // insert 后 user 对象可能不包含 ID，如果需要，需要配置 MyBatis 返回 ID 或重新查询
        return user;
    }

    @Override
    public User login(String username, String password) {
        // 主要由 Spring Security 使用
        return userMapper.findByUsername(username);
    }

    // 新增：根据 ID 获取用户
    @Override
    public User getUserById(Long id) {
         User user = userMapper.findById(id);
         // 可以在这里添加用户不存在的检查
         // if (user == null) {
         //     throw new ResourceNotFoundException("User not found with id: " + id);
         // }
         return user;
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    // --- 添加 updateUserProfile 方法实现 ---
    @Override
    @Transactional
    public User updateUserProfile(User user) {
        // 可以在这里添加更多验证逻辑，例如邮箱格式
        userMapper.updateProfile(user); // 假设 mapper 有 updateProfile 方法
        return userMapper.findById(user.getId()); // 返回更新后的用户信息
    }
    // --- 结束添加 updateUserProfile 方法实现 ---

    // --- 添加 changePassword 方法实现 ---
    @Override
    @Transactional
    public boolean changePassword(String username, String currentPassword, String newPassword) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("User not found");
        }
        // 验证当前密码
        if (!passwordEncoder.matches(currentPassword, user.getPassword())) {
            throw new BadCredentialsException("Incorrect current password");
        }
        // 更新密码
        user.setPassword(passwordEncoder.encode(newPassword));
        userMapper.updatePassword(user.getId(), user.getPassword());
        return true; // Indicate success
    }
    // --- 结束添加 changePassword 方法实现 ---

    // --- 添加充值余额方法实现 ---
    @Override
    @Transactional
    public User rechargeBalance(Long userId, BigDecimal amount) {
        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("充值金额必须大于0");
        }
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        BigDecimal newBalance = user.getBalance().add(amount);
        userMapper.updateBalance(userId, newBalance);
        user.setBalance(newBalance); // 更新内存中的对象
        return user;
    }

    // --- 添加扣减余额方法实现 ---
    @Override
    @Transactional
    public User deductBalance(Long userId, BigDecimal amount) {
         if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
             throw new IllegalArgumentException("扣减金额必须大于0");
         }
         User user = userMapper.findById(userId);
         if (user == null) {
             throw new IllegalArgumentException("用户不存在");
         }
         if (user.getBalance().compareTo(amount) < 0) {
             throw new IllegalStateException("余额不足");
         }
         BigDecimal newBalance = user.getBalance().subtract(amount);
         userMapper.updateBalance(userId, newBalance);
         user.setBalance(newBalance); // 更新内存中的对象
         return user;
    }

    @Override
    @Transactional
    public User withdrawBalance(Long userId, BigDecimal amount) {
        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("提现金额必须大于0");
        }
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        if (user.getBalance().compareTo(amount) < 0) {
            throw new IllegalStateException("余额不足，无法提现");
        }
        BigDecimal newBalance = user.getBalance().subtract(amount);
        userMapper.updateBalance(userId, newBalance);
        user.setBalance(newBalance); // 更新内存中的对象
        return user;
    }

    // 管理员用户管理方法实现
    @Override
    public List<User> getUsersPaged(int page, int size) {
        int offset = (page - 1) * size;
        return userMapper.findAllPaged(offset, size);
    }

    @Override
    public List<User> searchUsers(String keyword, int page, int size) {
        int offset = (page - 1) * size;
        return userMapper.searchUsers(keyword, offset, size);
    }

    @Override
    public int getUserCount() {
        return userMapper.count();
    }

    @Override
    public int getSearchUserCount(String keyword) {
        return userMapper.countSearchUsers(keyword);
    }
}